"""DNS数据模式."""

from datetime import datetime
from typing import Optional, List, Dict, Any

from pydantic import BaseModel, Field, validator


class DNSViewBase(BaseModel):
    """DNS视图基础模式."""
    
    name: str = Field(..., description="视图名称")
    description: Optional[str] = Field(None, description="描述信息")
    match_clients: Optional[str] = Field(None, description="客户端匹配规则")


class DNSViewCreate(DNSViewBase):
    """DNS视图创建模式."""
    pass


class DNSViewResponse(DNSViewBase):
    """DNS视图响应模式."""
    
    id: int = Field(..., description="视图ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    class Config:
        orm_mode = True


class DNSZoneBase(BaseModel):
    """DNS区域基础模式."""
    
    name: str = Field(..., description="区域名称")
    zone_type: str = Field("master", description="区域类型")
    primary_ns: Optional[str] = Field("ns1.example.com", description="主DNS服务器")
    admin_email: Optional[str] = Field("admin.example.com", description="管理员邮箱")
    refresh: int = Field(3600, description="刷新间隔")
    retry: int = Field(900, description="重试间隔")
    expire: int = Field(86400, description="过期时间")
    minimum_ttl: int = Field(300, description="最小TTL")
    view_id: Optional[int] = Field(None, description="视图ID")
    is_active: bool = Field(True, description="是否激活")

    @validator("zone_type")
    def validate_zone_type(cls, v):
        if v not in ["master", "slave", "forward"]:
            raise ValueError("zone_type must be master, slave, or forward")
        return v


class DNSZoneCreate(DNSZoneBase):
    """DNS区域创建模式."""
    pass


class DNSZoneUpdate(BaseModel):
    """DNS区域更新模式."""
    
    primary_ns: Optional[str] = Field(None, description="主DNS服务器")
    admin_email: Optional[str] = Field(None, description="管理员邮箱")
    refresh: Optional[int] = Field(None, description="刷新间隔")
    retry: Optional[int] = Field(None, description="重试间隔")
    expire: Optional[int] = Field(None, description="过期时间")
    minimum_ttl: Optional[int] = Field(None, description="最小TTL")
    is_active: Optional[bool] = Field(None, description="是否激活")


class DNSZoneResponse(DNSZoneBase):
    """DNS区域响应模式."""
    
    id: int = Field(..., description="区域ID")
    serial: int = Field(..., description="序列号")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    class Config:
        orm_mode = True


class DNSRecordBase(BaseModel):
    """DNS记录基础模式."""
    
    zone_id: int = Field(..., description="区域ID")
    name: str = Field(..., description="记录名称")
    record_type: str = Field(..., description="记录类型")
    value: str = Field(..., description="记录值")
    ttl: int = Field(3600, description="TTL值")
    priority: Optional[int] = Field(None, description="优先级")
    ip_address_id: Optional[int] = Field(None, description="关联的IP地址ID")
    is_active: bool = Field(True, description="是否激活")

    @validator("record_type")
    def validate_record_type(cls, v):
        valid_types = {"A", "AAAA", "CNAME", "MX", "TXT", "PTR", "NS", "SOA"}
        if v not in valid_types:
            raise ValueError(f"record_type must be one of {valid_types}")
        return v


class DNSRecordCreate(DNSRecordBase):
    """DNS记录创建模式."""
    pass


class DNSRecordUpdate(BaseModel):
    """DNS记录更新模式."""
    
    value: Optional[str] = Field(None, description="记录值")
    ttl: Optional[int] = Field(None, description="TTL值")
    priority: Optional[int] = Field(None, description="优先级")
    is_active: Optional[bool] = Field(None, description="是否激活")


class DNSRecordResponse(DNSRecordBase):
    """DNS记录响应模式."""
    
    id: int = Field(..., description="记录ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    
    class Config:
        orm_mode = True


class DNSQueryRequest(BaseModel):
    """DNS查询请求模式."""
    
    name: str = Field(..., description="域名")
    record_type: str = Field("A", description="记录类型")
    zone_name: Optional[str] = Field(None, description="指定区域名称")

    @validator("record_type")
    def validate_record_type(cls, v):
        valid_types = {"A", "AAAA", "CNAME", "MX", "TXT", "PTR", "NS"}
        if v not in valid_types:
            raise ValueError(f"record_type must be one of {valid_types}")
        return v


class DNSQueryResponse(BaseModel):
    """DNS查询响应模式."""
    
    name: str = Field(..., description="查询的域名")
    record_type: str = Field(..., description="记录类型")
    records: List[Dict[str, Any]] = Field(..., description="DNS记录列表")
    
    class Config:
        orm_mode = True


class ZoneStats(BaseModel):
    """区域统计信息."""
    
    total_records: int = Field(..., description="总记录数")
    record_types: Dict[str, int] = Field(..., description="按类型统计")
    active_records: int = Field(..., description="活跃记录数")
    inactive_records: int = Field(..., description="非活跃记录数")


class ZoneValidation(BaseModel):
    """区域验证结果."""
    
    valid: bool = Field(..., description="是否有效")
    errors: List[str] = Field(default_factory=list, description="错误信息")
    warnings: List[str] = Field(default_factory=list, description="警告信息")


class ZoneExport(BaseModel):
    """区域导出模式."""
    
    zone_name: str = Field(..., description="区域名称")
    content: str = Field(..., description="BIND格式配置内容")
    serial: int = Field(..., description="序列号")
    created_at: datetime = Field(..., description="导出时间")